循环与 Promise.all 结合

在开发中,我们可能需要循环调用接口,以获取数据。

前面我们说到:forEach 里面如果实现 async 同步效果,实际还是异步执行

如果我们使用 for 循环 + async/await ,可以实现同步,但耗时较久,比如一个请求1s,10个请求,则需要10s

Promise.all + map

我们可以使用 Promise.all + map,Promise.all 是异步请求并行执行

1
await Promise.all(arr.map(async (item, index) => await getData(index)))